#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023-04-18 10:44
# @Author  : wsh
# @File    : sms.py

import random
from datetime import datetime
import hashlib
import base64
import json

import requests


class CustomSMS:
    """发送短信类"""
    base_url = "https://app.cloopen.com:8883"
    # "/2013-12-26/Accounts/{accountSid}/SMS/TemplateSMS?sig={SigParameter}"
    work_url = "/2013-12-26/Accounts/{}/SMS/TemplateSMS?sig={}".format
    account_id = "8a216da87ba59937017bb06bfc4a0163"
    auth_token = "2bcbb1f217ce46d0add220acaa668c86"
    app_id = "8a216da87ba59937017bb06bfd43016a"

    def send_sms(self, to, code):
        """
        to: send message to ?
        data: ["code", "duration"]
        """
        time_stamp = self.get_time_stamp()
        request_url = self.get_post_url(time_stamp)
        headers = self.get_headers(time_stamp)
        post_data = self.get_post_data(to, code)
        response = requests.post(url=request_url, headers=headers, data=post_data)
        response_data = json.loads(response.text)
        print(response_data)
        if response_data['statusCode'] == '000000':
            return {
                'res': True,
                'message': '短信发送成功'
            }
        else:
            return {
                'res': False,
                'message': '短信发送失败，请稍后再试'
            }


    def get_post_url(self, time_stamp):
        """返回完整的url"""
        sign_parameter = self.account_id + self.auth_token + time_stamp
        m = hashlib.md5(sign_parameter.encode())
        sign_parameter = m.hexdigest().upper()
        request_url = self.base_url + self.work_url(self.account_id, sign_parameter)
        return request_url

    @staticmethod
    def get_time_stamp():
        time_now = datetime.now()
        time_stamp = datetime.strftime(time_now, "%Y%m%d%H%M%S")
        return time_stamp

    def get_headers(self, time_stamp):
        authorization = base64.urlsafe_b64encode((self.account_id + ":" + time_stamp).encode())
        return {
            "Accept": "application/json",
            "Content-Type": "application/json;charset=utf-8",
            "Content-Length": "256",
            "Authorization": authorization
        }

    def get_post_data(self, to: str, code: str):
        post_data = {
            "to": to,
            "appId": self.app_id,
            # "reqId": "abc123",
            # "subAppend": "8888",
            "templateId": "1",
            "datas": [
                code, "10"
            ]
        }
        return json.dumps(post_data)

    @staticmethod
    def create_code():
        basic_num = "0123456789"
        code = "".join(random.choices(basic_num, k=6))
        return code


custom_sms = CustomSMS()
custom_sms.send_sms("17839952415", "2222")